package org.truenewx.tnxjee.webmvc.menu;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.stereotype.Component;
import org.truenewx.tnxjee.core.Strings;
import org.truenewx.tnxjee.core.util.FileExtensions;
import org.truenewx.tnxjee.core.util.LogUtil;
import org.truenewx.tnxjee.model.spec.menu.Menu;

/**
 * 菜单模板加载器实现
 *
 * @author jianglei
 */
@Component
public class MenuTemplateLoaderImpl implements MenuTemplateLoader {

    private ApplicationContext context;
    private Map<String, MenuParser> parsers = new HashMap<>();

    public MenuTemplateLoaderImpl(ApplicationContext context) throws IOException {
        this.context = context;
        this.parsers.put(FileExtensions.JSON, new MenuJsonParser());
        this.parsers.put(FileExtensions.XML, new MenuXmlParser(context));
    }

    @Override
    public List<Menu> load() {
        List<Menu> menus = new ArrayList<>();
        try {
            ResourcePatternResolver resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(
                    this.context);
            Resource[] resources = resourcePatternResolver.getResources(
                    ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "menu/*");
            for (Resource resource : resources) {
                String fileName = resource.getFilename();
                if (fileName != null) {
                    int index = fileName.lastIndexOf(Strings.DOT);
                    String extension = fileName.substring(index + 1).toLowerCase();
                    MenuParser parser = this.parsers.get(extension);
                    if (parser != null) {
                        try (InputStream in = resource.getInputStream()) {
                            Menu menu = parser.parse(in);
                            if (StringUtils.isBlank(menu.getName())) {
                                String name = fileName.substring(0, index);
                                menu.setName(name);
                            }
                            menus.add(menu);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogUtil.error(getClass(), e);
        }
        return menus;
    }

}
